package com.tanhua.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.domain.AnalysisByDay;
import com.tanhua.domain.Log;
import com.tanhua.mapper.LogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class LogService extends ServiceImpl<LogMapper, Log> {
    @Autowired
    private AnalysisService analysisService;

        /**
         * 分析日志，统计分析数据存储到tb_analysis_by_day表
         */
        public void analysis() {
            //获取当前时间
            Date date = new Date();
            String today = DateUtil.format(date, "yyyy-MM-dd");
            String yesterday = DateUtil.offsetDay(date, -1).toDateStr();

            AnalysisByDay analysis = analysisService.query().eq("record_date", today).one();
            if (analysis == null) {
                analysis = new AnalysisByDay();
                analysis.setRecordDate(date);
                analysis.setCreated(date);
                analysis.setUpdated(date);

                analysisService.save(analysis);
            }
            //统计数据
            //今日新增用户数
            Integer numRegistered = query().eq("type", "0102").eq("log_time", today).select("distinct user_id").count();
            analysis.setNumRegistered(numRegistered);

            //今日登录次数
            Integer numLogin = query().eq("type", "0101").eq("log_time", today).select("distinct user_id").count();
            analysis.setNumLogin(numLogin);

            //今日活跃用户数
            Integer active = query().eq("log_time", today).select("distinct user_id").count();
            analysis.setNumActive(active);

            //次日留存用户数
            int retention = baseMapper.queryRetentionCount(today, yesterday);
            analysis.setNumRetention1d(retention);

            analysisService.updateById(analysis);
        }
    }

